<template>
	<view>
		<view class="cu-custom" :style="{'height':customBarHeight + 'px'}">
			<view class="cu-bar fixed"
				:style="{'height':customBarHeight + 'px','padding-top':statusBarHeight + 'px','background-color':themeConfig.primaryColor}">
				<view :style="{color : themeConfig.commonColor}" class=" margin-left-sm" @tap="tapScan()">
					<view class="cuIcon-scan" style="font-size: 45rpx;"></view>
				</view>
				<view class="search-form round" style="width:60rpx;height:60rpx;margin: 10rpx 20rpx;">
					<text class="cuIcon-search text-gray" style=";font-size: 36rpx;"></text>
					<input style="width:60rpx;height:60rpx;" type="text" confirm-type="search" @confirm="tapSearchName"
						:value="searchName" @input="searchNameInputChange" />
					<view v-if="searchName!=''" class="cuIcon-roundclosefill text-gray" style="font-size: 40rpx;"
						@tap="deleteSearchName"></view>
				</view>
				<button v-if="isShowSearchButton" class="cu-btn bg-gradual-green round margin-right-xs"
					@tap="tapSearchName">{{$t('search')}}</button>
			</view>
		</view>
		<view id="navScroll">
			<scroll-view scroll-x class="bg-white nav fixed" :style="{'margin-top':customBarHeight + 'px'}"
				scroll-with-animation>
				<view class="flex text-center" :style="{color : themeConfig.primaryColor}">
					<view class="cu-item flex-sub">
						<picker @change="statusChange" :value="statusIndex" :range='statusList' range-key="label">
							<view class="text-df">
								{{formatStatusIndex(statusIndex).label}}
							</view>
						</picker>
					</view>
					<view class="cu-item flex-sub">
						<picker mode="multiSelector" @change="productAndSeriesChange"
							@columnchange="productAndSeriesColumnchange" :value="productAndSeriesIndex"
							:range='productAndSeriesNameList'>
							<view class="text-df">
								{{productAndSeriesNameList[0][productAndSeriesIndex[0]]}} [
								{{productAndSeriesNameList[1][productAndSeriesIndex[1]]}} ]
							</view>
						</picker>
					</view>
					<view class="cu-item flex-sub" v-if="pageList.length != 0">
						<picker @change="pageChange" :value="currentPageIndex" :range='pageList'>
							<view class="text-df">
								{{pageList[currentPageIndex]}}
							</view>
						</picker>
					</view>
					<view class="cu-item flex-sub text-df">|</view>
					<view class="cu-item flex-sub" v-if="!websiteModel || websiteModel==='user'">
						<view v-if="follow" class="cuIcon-likefill text-bold text-center" @tap="followChange(null)"
							style="font-size:32rpx;"></view>
						<view v-else class="cuIcon-like text-bold text-center" @tap="followChange(true)"
							style="font-size:32rpx;"></view>
					</view>
					<view class="cu-item flex-sub">
						<view v-if="warnDesc" class="cuIcon-warnfill text-bold text-center" @tap="warnDescChange(null)"
							style="font-size:32rpx;"></view>
						<view v-else class="cuIcon-warn text-bold text-center" @tap="warnDescChange(true)"
							style="font-size:32rpx;"></view>
					</view>
					<view class="cu-item flex-sub">
						<view v-if="listModel === 'list'" class="cuIcon-cascades text-bold text-center"
							@tap="listModelChange('block')" style="font-size:32rpx;"></view>
						<view v-else class="cuIcon-list text-bold text-center" @tap="listModelChange('list')"
							style="font-size:32rpx;"></view>
					</view>
				</view>
			</scroll-view>
		</view>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="downOption" @down="downCallback" :up="upOption"
			@up="pageGetDevice">
			<view class="bg-white"
				:style="{'margin-top':(customBarHeight + navScrollHeight - statusBarHeight + 5)+'px'}">
				<view v-if="listModel === 'list'">
					<view v-for="(arrItem,arrIndex) in deviceList" :key="arrIndex">
						<view v-for="(item,index) in arrItem" :key="index" @tap='deviceNavigation(item)'>
							<device-list-item :device="item"></device-list-item>
						</view>
					</view>
				</view>
				<view v-else>
					<view v-for="(arrItem,arrIndex) in deviceList" :key="arrIndex">
						<view
							style="display: grid;grid-template-columns:1fr 1fr;grid-template-rows 1fr 1fr;grid-auto-flow : row dense;grid-column-gap: 5rpx;">
							<view v-for="(item,index) in arrItem" :key="index" @tap='deviceNavigation(item)'
								style="grid-column-start: span 1;border-radius:10rpx;"
								class="bg-gray padding-xs margin-xs">
								<view class="bg-white padding-top-xs" style="border-radius:10rpx;height: 130rpx;">
									<view style="float: right;"
										:style="{color : item.status === 'ONLINE' ? '#0F0F0F' :'#AAAAAA'}"
										class="text-sm text-gray margin-right">
										{{ formatDeviceStatus(item.status) }}
									</view>
									<view style="width: 85rpx;margin: 10rpx auto;">
										<image style="width: 85rpx;height: 85rpx;" :src='item.iconUrl'></image>
									</view>
								</view>
								<view class="text-xs flex-sub margin-top-sm margin-bottom-sm">
									<view class="flex justify-between margin-left-xs">
										<view>
											<text class="text-bold text-sm" :style="{color : themeConfig.primaryColor}">
												{{item.deviceName}}
											</text>
											<view class="text-cut text-gray text-xs margin-top-xs">
												<text v-if="item.warnNum > 0"
													class="cuIcon-infofill text-red margin-right-xs"></text>{{item.deviceCore}}
											</view>
										</view>
										<view
											class="cuIcon-settingsfill text-bold text-center margin-top-sm margin-right-xs"
											@tap.stop='deviceSetting(item)' style="font-size:35rpx;"></view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-body>
		<view :style="[{paddingBottom:`${tabbarHeight}px`}]"></view>
	</view>
</template>

<script>
	import {
		showToast
	} from '@/util/toast.js'
	import {
		commonScanHandle,
		listProductList,
		listProductSeries,
		listDeviceStatus,
		formatDeviceStatus
	} from '@/util/utils.js'
	import * as iotDeviceBelongApi from '@/api/iot/iotDeviceBelongApi.js'
	import * as iotDeviceApi from '@/api/iot/iotDeviceApi.js'
	import * as iotProductApi from '@/api/iot/iotProductApi.js'
	import * as iotProductSeriesApi from '@/api/iot/iotProductSeriesApi.js'
	import * as iotProductUserApi from '@/api/iot/iotProductUserApi.js'
	import * as iotProductSeriesUserApi from '@/api/iot/iotProductSeriesUserApi.js'
	import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
	import * as ztnNativeFunction from '@/util/ztnNativeFunction.js'
	import DeviceListItem from '@/components/ztn-custom/DeviceListItem/index.vue'
	import * as storage from '@/util/storage.js'
	export default {
		name: 'DeviceList',
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
		data() {
			return {
				downOption: {
					use: true,
					auto: false //是否在初始化后,自动执行downCallback; 默认true
				},
				upOption: {
					use: true,
					auto: false,
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					empty: {
						use: true,
						fixed: true,
						top: '25%'
					},
				},
				imageSrc: '/static/images/noContent.png',
				navScrollHeight: 0,
				isShowSearchButton: false,
				productList: [],
				productSeriesList: [],
				productAndSeriesList: [
					[],
					[]
				],
				productAndSeriesNameList: [
					[],
					[]
				],
				pageList: [],
				statusIndex: 0,
				statusList: [],
				productAndSeriesIndex: [0, 0],
				currentPageIndex: 0,
				deviceList: [],
				device: {},
				productId: null,
				seriesId: null,
				searchName: null,
				warnDesc: null,
				follow: null,
				listModel: 'list',
				currentPage: 1,
				pageSize: 10,
				userId: storage.getUserId(),
				companyId: storage.getCompanyId(),
				deptId: storage.getDeptId(),
				websiteModel: storage.getWebsiteModel(),
				customBarHeight: storage.getCustomBarHeight(),
				statusBarHeight: storage.getStatusBarHeight(),
				tabbarHeight: storage.getTabbarHeight(),
			}
		},
		name: 'DeviceList',
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			formatDeviceStatus(status) {
				return formatDeviceStatus(this, status)
			},
			formatStatusIndex(index) {
				return this.statusList[index]
			},
			statusChange(e) {
				this.statusIndex = e.detail.value
				storage.setStatusIndex(this.statusIndex)
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			listModelChange(listModel) {
				this.listModel = listModel
				storage.setListModel(this.listModel)
			},
			tapScan() {
				// #ifdef H5
				ztnNativeFunction.scanErcode({
					success: (res) => {
						commonScanHandle(this, res)
					},
					fail: (res) => {
						showToast(this.$t('failure'), 'none', 1000, false) //操作失败
					}
				})
				// #endif
				// #ifndef H5
				uni.scanCode({
					success: (res) => {
						commonScanHandle(this, res.result)
					},
					fail: (res) => {
						showToast(this.$t('failure'), 'none', 1000, false) //操作失败
					}
				});
				// #endif
			},
			init() {
				this.statusList = listDeviceStatus(this)
				this.statusIndex = storage.getStatusIndex()
				this.searchName = storage.getSearchDeviceName()
				this.warnDesc = storage.getWarnDesc()
				this.follow = storage.getFollow()
				this.listModel = storage.getListModel()
				const productId = storage.getProductId()
				if (productId) {
					this.productId = parseInt(productId)
				}
				uni.createSelectorQuery().in(this).select('#navScroll')
					.boundingClientRect((e) => {
						this.navScrollHeight = e.height
					}).exec()
				this.listProductAndSeries().then(res => {
					this.productAndSeriesList = [this.productList, this.productSeriesList]
					const index = this.productList.findIndex((item) => item.productId === this.productId)
					this.productAndSeriesIndex = [index, 0]
				})
				this.pageGetDevice()
			},
			downCallback() {
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.resetUpScroll()
			},
			listProductAndSeries: async function() {
				let api
				switch (this.websiteModel) {
					case 'system':
					case 'company':
					case 'dept':
						api = iotProductApi.listProduct({})
						break
					default:
						api = iotProductUserApi.listProduct({
							userId: this.userId
						})
				}

				await api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.productList = listProductList(this, data)
					}
				})


				if (this.productId) {
					await this.listSeries();
				} else {
					this.handleProductSeriesList([])
				}
			},
			listSeries() {
				return new Promise((resolve, reject) => {
					let api
					switch (this.websiteModel) {
						case 'system':
						case 'company':
						case 'dept':
							api = iotProductSeriesApi.listSeries({
								productId: this.productId
							})
							break
						default:
							api = iotProductSeriesUserApi.listSeries({
								userId: this.userId,
								productId: this.productId
							})
					}
					api.then((res) => {
						const {
							data
						} = res
						if (data) {
							this.handleProductSeriesList(data)
							resolve()
						}
					})
				})
			},
			makeProductAndSeriesNameList() {
				const productNameList = []
				this.productList.forEach(item => {
					productNameList.push(item.name)
				})
				const productSeriesNameList = []
				this.productSeriesList.forEach(item => {
					productSeriesNameList.push(item.name)
				})
				this.productAndSeriesNameList = [productNameList, productSeriesNameList]
			},
			handleProductSeriesList(data) {
				this.productSeriesList = listProductSeries(this, data)
				this.makeProductAndSeriesNameList()
			},
			pageGetDevice() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.pageGetAllDevice({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							deviceName: this.searchName,
							warnDesc: this.warnDesc,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'company':
						api = iotDeviceApi.pageGetCompanyDevice({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							deviceName: this.searchName,
							warnDesc: this.warnDesc,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'dept':
						api = iotDeviceApi.pageGetDeptDevice({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							deviceName: this.searchName,
							warnDesc: this.warnDesc,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					default:
						api = iotDeviceBelongApi.pageGetDevice({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							deviceName: this.searchName,
							warnDesc: this.warnDesc,
							follow: this.follow,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
				}


				api.then((res) => {
					if (res.data) {
						const {
							currentPage,
							data,
							total
						} = res.data

						const lastPage = Math.ceil(total / this.pageSize)
						const pageList = [];
						for (let i = 1; i <= lastPage; i++) {
							pageList.push(this.$i18n.locale == 'en' ? this.$t('page') + i : i + this
								.$t('page'))
						}
						this.pageList = pageList
						this.mescroll.endSuccess(data.length, currentPage < lastPage)
						const index = currentPage - 1
						this.$set(this.deviceList, index, data)
						this.currentPageIndex = index
						if (currentPage < lastPage) {
							this.currentPage = currentPage + 1
						}
					}
				})
			},
			productAndSeriesColumnchange(e) {
				// console.log('修改的列为：' + e.detail.column + '，值为：' + e.detail.value)
				const column = e.detail.column
				const value = e.detail.value
				switch (column) {
					case 0: //拖动第1列
						if (value != 0) {
							this.productId = this.productList[value].productId
							this.listSeries().then((res) => {
								this.productAndSeriesIndex = [value, 0]
							})
						} else {
							this.productAndSeriesIndex = [0, 0]
						}
						break;
					case 1:
						this.productAndSeriesIndex = [this.productAndSeriesIndex[0], value]
						break
					default:
						break;
				}
				this.$forceUpdate()
			},
			productAndSeriesChange(e) {
				const index = e.detail.value
				this.productAndSeriesIndex = index
				this.productId = this.productList[index[0]].productId
				storage.setProductId(this.productId)
				this.seriesId = this.productSeriesList[index[1]].seriesId
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			warnDescChange(warnDesc) {
				this.warnDesc = warnDesc
				storage.setWarnDesc(this.warnDesc)
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			followChange(follow) {
				this.follow = follow
				storage.setFollow(this.follow)
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			pageChange(e) {
				let index = e.detail.value
				this.currentPageIndex = index
				this.currentPage = parseInt(index) + 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			searchNameInputChange(e) {
				const value = e.detail.value.replace(/\s/g, '')
				if (value == '') {
					this.deleteSearchName()
				} else {
					this.searchName = value
					this.isShowSearchButton = true
				}
			},
			deleteSearchName(e) {
				this.searchName = ''
				storage.setSearchDeviceName(this.searchName)
				this.isShowSearchButton = false
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			tapSearchName() {
				storage.setSearchDeviceName(this.searchName)
				this.isShowSearchButton = false
				this.currentPage = 1
				this.deviceList = []
				this.mescroll.scrollTo(0, 300)
				this.mescroll.resetUpScroll()
			},
			deviceNavigation(item) {
				const component = storage.getDeviceNavigationComponent()
				uni.navigateTo({
					url: `/pages/deviceNavigation/deviceNavigation?deviceCore=${item.deviceCore}&component=${component}`
				})
			},
			deviceSetting(item) {
				uni.navigateTo({
					url: `/pages/deviceNavigation/deviceNavigation?deviceCore=${item.deviceCore}&component=deviceSetting`
				})
			}
		},
		components: {
			DeviceListItem,

		}
	}
</script>
